{
 "cells": [
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "# Deep Kernel Learning (DenseNet + GP) on CIFAR10/100\n",
    "\n",
    "In this notebook, we'll demonstrate the steps necessary to train a medium sized DenseNet (https://arxiv.org/abs/1608.06993) on either of two popularly used benchmark dataset in computer vision (CIFAR10 and CIFAR100). We'll be training the DKL model entirely end to end using the standard 300 Epoch training schedule and SGD.\n",
    "\n",
    "This notebook is largely for tutorial purposes. If your goal is just to get (for example) a trained DKL + CIFAR100 model, we __recommend__ that you move this code to a simple python script and run that, rather than training directly out of a python notebook. We find that training is just a bit faster out of a python notebook. We also of course recommend that you increase the size of the DenseNet used to a full sized model if you would like to achieve state of the art performance.\n",
    "\n",
    "Furthermore, because this notebook involves training an actually reasonably large neural network, it is __strongly recommended__ that you have a decent GPU available for this, as with all large deep learning models."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 1,
   "metadata": {},
   "outputs": [],
   "source": [
    "from torch.optim import SGD, Adam\n",
    "from torch.optim.lr_scheduler import MultiStepLR\n",
    "import torch.nn.functional as F\n",
    "from torch import nn\n",
    "import torch\n",
    "import torchvision.datasets as dset\n",
    "import torchvision.transforms as transforms\n",
    "import gpytorch\n",
    "import math"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Set up data augmentation\n",
    "\n",
    "The first thing we'll do is set up some data augmentation transformations to use during training, as well as some basic normalization to use during both training and testing. We'll use random crops and flips to train the model, and do basic normalization at both training time and test time. To accomplish these transformations, we use standard `torchvision` transforms."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 2,
   "metadata": {},
   "outputs": [],
   "source": [
    "normalize = transforms.Normalize(mean=[0.5071, 0.4867, 0.4408], std=[0.2675, 0.2565, 0.2761])\n",
    "aug_trans = [transforms.RandomCrop(32, padding=4), transforms.RandomHorizontalFlip()]\n",
    "common_trans = [transforms.ToTensor(), normalize]\n",
    "train_compose = transforms.Compose(aug_trans + common_trans)\n",
    "test_compose = transforms.Compose(common_trans)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Create DataLoaders\n",
    "\n",
    "Next, we create dataloaders for the selected dataset using the built in torchvision datasets. The cell below will download either the cifar10 or cifar100 dataset, depending on which choice is made. The default here is cifar10, however training is just as fast on either dataset.\n",
    "\n",
    "After downloading the datasets, we create standard `torch.utils.data.DataLoader`s for each dataset that we will be using to get minibatches of augmented data."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 3,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Files already downloaded and verified\n"
     ]
    }
   ],
   "source": [
    "dataset = 'cifar10'\n",
    "\n",
    "if dataset == 'cifar10':\n",
    "    d_func = dset.CIFAR10\n",
    "    train_set = dset.CIFAR10('data', train=True, transform=train_compose, download=True)\n",
    "    test_set = dset.CIFAR10('data', train=False, transform=test_compose)\n",
    "    train_loader = torch.utils.data.DataLoader(train_set, batch_size=256, shuffle=True)\n",
    "    test_loader = torch.utils.data.DataLoader(test_set, batch_size=256, shuffle=False)\n",
    "    num_classes = 10\n",
    "elif dataset == 'cifar100':\n",
    "    d_func = dset.CIFAR100\n",
    "    train_set = dset.CIFAR100('data', train=True, transform=train_compose, download=True)\n",
    "    test_set = dset.CIFAR100('data', train=False, transform=test_compose)\n",
    "    train_loader = torch.utils.data.DataLoader(train_set, batch_size=256, shuffle=True)\n",
    "    test_loader = torch.utils.data.DataLoader(test_set, batch_size=256, shuffle=False)\n",
    "    num_classes = 100\n",
    "else:\n",
    "    raise RuntimeError('dataset must be one of \"cifar100\" or \"cifar10\"')"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Creating the DenseNet Model\n",
    "\n",
    "With the data loaded, we can move on to defining our DKL model. A DKL model consists of three components: the neural network, the Gaussian process layer used after the neural network, and the Softmax likelihood.\n",
    "\n",
    "The first step is defining the neural network architecture. To do this, we use a slightly modified version of the DenseNet available in the standard PyTorch package. Specifically, we modify it to remove the softmax layer, since we'll only be needing the final features extracted from the neural network."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 4,
   "metadata": {},
   "outputs": [],
   "source": [
    "from densenet import DenseNet\n",
    "\n",
    "class DenseNetFeatureExtractor(DenseNet):\n",
    "    def forward(self, x):\n",
    "        features = self.features(x)\n",
    "        out = F.relu(features, inplace=True)\n",
    "        out = F.avg_pool2d(out, kernel_size=self.avgpool_size).view(features.size(0), -1)\n",
    "        return out\n",
    "\n",
    "feature_extractor = DenseNetFeatureExtractor(block_config=(6, 6, 6), num_classes=num_classes).cuda()\n",
    "num_features = feature_extractor.classifier.in_features"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Creating the GP Layer\n",
    "\n",
    "In the next cell, we create the layer of Gaussian process models that are called after the neural network. In this case, we'll be using one GP per feature, as in the SV-DKL paper. The outputs of these Gaussian processes will the be mixed in the softmax likelihood."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 5,
   "metadata": {},
   "outputs": [],
   "source": [
    "class GaussianProcessLayer(gpytorch.models.AbstractVariationalGP):\n",
    "    def __init__(self, num_dim, grid_bounds=(-10., 10.), grid_size=64):\n",
    "        variational_distribution = gpytorch.variational.CholeskyVariationalDistribution(\n",
    "            num_inducing_points=grid_size, batch_size=num_dim\n",
    "        )\n",
    "        variational_strategy = gpytorch.variational.AdditiveGridInterpolationVariationalStrategy(\n",
    "            self, grid_size=grid_size, grid_bounds=[grid_bounds], num_dim=num_dim,\n",
    "            variational_distribution=variational_distribution, mixing_params=False, sum_output=False\n",
    "        )\n",
    "        super().__init__(variational_strategy)\n",
    "        \n",
    "        self.covar_module = gpytorch.kernels.ScaleKernel(\n",
    "            gpytorch.kernels.RBFKernel(\n",
    "                lengthscale_prior=gpytorch.priors.SmoothedBoxPrior(\n",
    "                    math.exp(-1), math.exp(1), sigma=0.1, transform=torch.exp\n",
    "                )\n",
    "            )\n",
    "        )\n",
    "        self.mean_module = gpytorch.means.ConstantMean()\n",
    "        self.grid_bounds = grid_bounds\n",
    "\n",
    "    def forward(self, x):\n",
    "        mean = self.mean_module(x)\n",
    "        covar = self.covar_module(x)\n",
    "        return gpytorch.distributions.MultivariateNormal(mean, covar)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Creating the DKL Model\n",
    "\n",
    "With both the DenseNet feature extractor and GP layer defined, we can put them together in a single module that simply calls one and then the other, much like building any Sequential neural network in PyTorch. This completes defining our DKL model."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 6,
   "metadata": {},
   "outputs": [],
   "source": [
    "class DKLModel(gpytorch.Module):\n",
    "    def __init__(self, feature_extractor, num_dim, grid_bounds=(-10., 10.)):\n",
    "        super(DKLModel, self).__init__()\n",
    "        self.feature_extractor = feature_extractor\n",
    "        self.gp_layer = GaussianProcessLayer(num_dim=num_dim, grid_bounds=grid_bounds)\n",
    "        self.grid_bounds = grid_bounds\n",
    "        self.num_dim = num_dim\n",
    "\n",
    "    def forward(self, x):\n",
    "        features = self.feature_extractor(x)\n",
    "        features = gpytorch.utils.grid.scale_to_bounds(features, self.grid_bounds[0], self.grid_bounds[1])\n",
    "        res = self.gp_layer(features)\n",
    "        return res\n",
    "\n",
    "model = DKLModel(feature_extractor, num_dim=num_features).cuda()\n",
    "likelihood = gpytorch.likelihoods.SoftmaxLikelihood(num_features=model.num_dim, num_classes=num_classes).cuda()"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Defining Training and Testing Code\n",
    "\n",
    "Next, we define the basic optimization loop and testing code. This code is entirely analogous to the standard PyTorch training loop. We create a `torch.optim.SGD` optimizer with the parameters of the neural network on which we apply the standard amount of weight decay suggested from the paper, the parameters of the Gaussian process (from which we omit weight decay, as L2 regualrization on top of variational inference is not necessary), and the mixing parameters of the Softmax likelihood. \n",
    "\n",
    "We use the standard learning rate schedule from the paper, where we decrease the learning rate by a factor of ten 50% of the way through training, and again at 75% of the way through training."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 7,
   "metadata": {},
   "outputs": [],
   "source": [
    "n_epochs = 300\n",
    "lr = 0.1\n",
    "optimizer = SGD([\n",
    "    {'params': model.feature_extractor.parameters(), 'weight_decay': 1e-4},\n",
    "    {'params': model.gp_layer.hyperparameters(), 'lr': lr * 0.01},\n",
    "    {'params': model.gp_layer.variational_parameters()},\n",
    "    {'params': likelihood.parameters()},\n",
    "], lr=lr, momentum=0.9, nesterov=True, weight_decay=0)\n",
    "scheduler = MultiStepLR(optimizer, milestones=[0.5 * n_epochs, 0.75 * n_epochs], gamma=0.1)\n",
    "mll = gpytorch.mlls.VariationalELBO(likelihood, model.gp_layer, num_data=len(train_loader.dataset))\n",
    "\n",
    "\n",
    "def train(epoch):\n",
    "    model.train()\n",
    "    likelihood.train()\n",
    "\n",
    "    train_loss = 0.\n",
    "    for batch_idx, (data, target) in enumerate(train_loader):\n",
    "        data, target = data.cuda(), target.cuda()\n",
    "        optimizer.zero_grad()\n",
    "        output = model(data)\n",
    "        loss = -mll(output, target)\n",
    "        loss.backward()\n",
    "        optimizer.step()\n",
    "        if (batch_idx + 1) % 25 == 0:\n",
    "            print('Train Epoch: %d [%03d/%03d], Loss: %.6f' % (epoch, batch_idx + 1, len(train_loader), loss.item()))\n",
    "\n",
    "def test():\n",
    "    model.eval()\n",
    "    likelihood.eval()\n",
    "\n",
    "    correct = 0\n",
    "    with torch.no_grad(), gpytorch.settings.num_likelihood_samples(16):\n",
    "        for data, target in test_loader:\n",
    "            data, target = data.cuda(), target.cuda()\n",
    "            output = likelihood(model(data))  # This gives us 16 samples from the predictive distribution\n",
    "            pred = output.probs.mean(0).argmax(-1)  # Taking the mean over all of the sample we've drawn\n",
    "            correct += pred.eq(target.view_as(pred)).cpu().sum()\n",
    "    print('Test set: Accuracy: {}/{} ({}%)'.format(\n",
    "        correct, len(test_loader.dataset), 100. * correct / float(len(test_loader.dataset))\n",
    "    ))"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Train the Model\n",
    "\n",
    "We are now ready to train the model. At the end of each Epoch we report the current test loss and accuracy, and we save a checkpoint model out to a file."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 8,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Train Epoch: 1 [025/196], Loss: 2.302444\n",
      "Train Epoch: 1 [050/196], Loss: 2.301484\n",
      "Train Epoch: 1 [075/196], Loss: 2.290751\n",
      "Train Epoch: 1 [100/196], Loss: 2.188489\n",
      "Train Epoch: 1 [125/196], Loss: 1.953194\n",
      "Train Epoch: 1 [150/196], Loss: 1.906971\n",
      "Train Epoch: 1 [175/196], Loss: 1.758498\n",
      "Test set: Accuracy: 2195/10000 (21%)\n",
      "Train Epoch: 2 [025/196], Loss: 1.655540\n",
      "Train Epoch: 2 [050/196], Loss: 1.647960\n",
      "Train Epoch: 2 [075/196], Loss: 1.558461\n",
      "Train Epoch: 2 [100/196], Loss: 1.479025\n",
      "Train Epoch: 2 [125/196], Loss: 1.372020\n",
      "Train Epoch: 2 [150/196], Loss: 1.321366\n",
      "Train Epoch: 2 [175/196], Loss: 1.267039\n",
      "Test set: Accuracy: 4806/10000 (48%)\n",
      "Train Epoch: 3 [025/196], Loss: 1.240473\n",
      "Train Epoch: 3 [050/196], Loss: 1.126701\n",
      "Train Epoch: 3 [075/196], Loss: 0.965710\n",
      "Train Epoch: 3 [100/196], Loss: 1.073907\n",
      "Train Epoch: 3 [125/196], Loss: 1.031474\n",
      "Train Epoch: 3 [150/196], Loss: 1.050503\n",
      "Train Epoch: 3 [175/196], Loss: 0.924077\n",
      "Test set: Accuracy: 5200/10000 (52%)\n"
     ]
    },
    {
     "ename": "KeyboardInterrupt",
     "evalue": "",
     "output_type": "error",
     "traceback": [
      "\u001b[0;31m---------------------------------------------------------------------------\u001b[0m",
      "\u001b[0;31mKeyboardInterrupt\u001b[0m                         Traceback (most recent call last)",
      "\u001b[0;32m<ipython-input-8-6f7e8ea00fe7>\u001b[0m in \u001b[0;36m<module>\u001b[0;34m\u001b[0m\n\u001b[1;32m      2\u001b[0m     \u001b[0mscheduler\u001b[0m\u001b[0;34m.\u001b[0m\u001b[0mstep\u001b[0m\u001b[0;34m(\u001b[0m\u001b[0;34m)\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[1;32m      3\u001b[0m     \u001b[0;32mwith\u001b[0m \u001b[0mgpytorch\u001b[0m\u001b[0;34m.\u001b[0m\u001b[0msettings\u001b[0m\u001b[0;34m.\u001b[0m\u001b[0muse_toeplitz\u001b[0m\u001b[0;34m(\u001b[0m\u001b[0;32mFalse\u001b[0m\u001b[0;34m)\u001b[0m\u001b[0;34m:\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[0;32m----> 4\u001b[0;31m         \u001b[0mtrain\u001b[0m\u001b[0;34m(\u001b[0m\u001b[0mepoch\u001b[0m\u001b[0;34m)\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[0m\u001b[1;32m      5\u001b[0m         \u001b[0mtest\u001b[0m\u001b[0;34m(\u001b[0m\u001b[0;34m)\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[1;32m      6\u001b[0m     \u001b[0mstate_dict\u001b[0m \u001b[0;34m=\u001b[0m \u001b[0mmodel\u001b[0m\u001b[0;34m.\u001b[0m\u001b[0mstate_dict\u001b[0m\u001b[0;34m(\u001b[0m\u001b[0;34m)\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n",
      "\u001b[0;32m<ipython-input-7-a447f92a440d>\u001b[0m in \u001b[0;36mtrain\u001b[0;34m(epoch)\u001b[0m\n\u001b[1;32m     21\u001b[0m         \u001b[0moutput\u001b[0m \u001b[0;34m=\u001b[0m \u001b[0mmodel\u001b[0m\u001b[0;34m(\u001b[0m\u001b[0mdata\u001b[0m\u001b[0;34m)\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[1;32m     22\u001b[0m         \u001b[0mloss\u001b[0m \u001b[0;34m=\u001b[0m \u001b[0;34m-\u001b[0m\u001b[0mmll\u001b[0m\u001b[0;34m(\u001b[0m\u001b[0moutput\u001b[0m\u001b[0;34m,\u001b[0m \u001b[0mtarget\u001b[0m\u001b[0;34m)\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[0;32m---> 23\u001b[0;31m         \u001b[0mloss\u001b[0m\u001b[0;34m.\u001b[0m\u001b[0mbackward\u001b[0m\u001b[0;34m(\u001b[0m\u001b[0;34m)\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[0m\u001b[1;32m     24\u001b[0m         \u001b[0moptimizer\u001b[0m\u001b[0;34m.\u001b[0m\u001b[0mstep\u001b[0m\u001b[0;34m(\u001b[0m\u001b[0;34m)\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[1;32m     25\u001b[0m         \u001b[0;32mif\u001b[0m \u001b[0;34m(\u001b[0m\u001b[0mbatch_idx\u001b[0m \u001b[0;34m+\u001b[0m \u001b[0;36m1\u001b[0m\u001b[0;34m)\u001b[0m \u001b[0;34m%\u001b[0m \u001b[0;36m25\u001b[0m \u001b[0;34m==\u001b[0m \u001b[0;36m0\u001b[0m\u001b[0;34m:\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n",
      "\u001b[0;32m~/miniconda3/envs/gpytorch/lib/python3.6/site-packages/torch/tensor.py\u001b[0m in \u001b[0;36mbackward\u001b[0;34m(self, gradient, retain_graph, create_graph)\u001b[0m\n\u001b[1;32m    100\u001b[0m                 \u001b[0mproducts\u001b[0m\u001b[0;34m.\u001b[0m \u001b[0mDefaults\u001b[0m \u001b[0mto\u001b[0m\u001b[0;31m \u001b[0m\u001b[0;31m`\u001b[0m\u001b[0;31m`\u001b[0m\u001b[0;32mFalse\u001b[0m\u001b[0;31m`\u001b[0m\u001b[0;31m`\u001b[0m\u001b[0;34m.\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[1;32m    101\u001b[0m         \"\"\"\n\u001b[0;32m--> 102\u001b[0;31m         \u001b[0mtorch\u001b[0m\u001b[0;34m.\u001b[0m\u001b[0mautograd\u001b[0m\u001b[0;34m.\u001b[0m\u001b[0mbackward\u001b[0m\u001b[0;34m(\u001b[0m\u001b[0mself\u001b[0m\u001b[0;34m,\u001b[0m \u001b[0mgradient\u001b[0m\u001b[0;34m,\u001b[0m \u001b[0mretain_graph\u001b[0m\u001b[0;34m,\u001b[0m \u001b[0mcreate_graph\u001b[0m\u001b[0;34m)\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[0m\u001b[1;32m    103\u001b[0m \u001b[0;34m\u001b[0m\u001b[0m\n\u001b[1;32m    104\u001b[0m     \u001b[0;32mdef\u001b[0m \u001b[0mregister_hook\u001b[0m\u001b[0;34m(\u001b[0m\u001b[0mself\u001b[0m\u001b[0;34m,\u001b[0m \u001b[0mhook\u001b[0m\u001b[0;34m)\u001b[0m\u001b[0;34m:\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n",
      "\u001b[0;32m~/miniconda3/envs/gpytorch/lib/python3.6/site-packages/torch/autograd/__init__.py\u001b[0m in \u001b[0;36mbackward\u001b[0;34m(tensors, grad_tensors, retain_graph, create_graph, grad_variables)\u001b[0m\n\u001b[1;32m     88\u001b[0m     Variable._execution_engine.run_backward(\n\u001b[1;32m     89\u001b[0m         \u001b[0mtensors\u001b[0m\u001b[0;34m,\u001b[0m \u001b[0mgrad_tensors\u001b[0m\u001b[0;34m,\u001b[0m \u001b[0mretain_graph\u001b[0m\u001b[0;34m,\u001b[0m \u001b[0mcreate_graph\u001b[0m\u001b[0;34m,\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[0;32m---> 90\u001b[0;31m         allow_unreachable=True)  # allow_unreachable flag\n\u001b[0m\u001b[1;32m     91\u001b[0m \u001b[0;34m\u001b[0m\u001b[0m\n\u001b[1;32m     92\u001b[0m \u001b[0;34m\u001b[0m\u001b[0m\n",
      "\u001b[0;31mKeyboardInterrupt\u001b[0m: "
     ]
    }
   ],
   "source": [
    "for epoch in range(1, n_epochs + 1):\n",
    "    scheduler.step()\n",
    "    with gpytorch.settings.use_toeplitz(False):\n",
    "        train(epoch)\n",
    "        test()\n",
    "    state_dict = model.state_dict()\n",
    "    likelihood_state_dict = likelihood.state_dict()\n",
    "    torch.save({'model': state_dict, 'likelihood': likelihood_state_dict}, 'dkl_cifar_checkpoint.dat')"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "We cut training short here. With more training - the network will get as good of accuracy as a standard neural network."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": []
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.6.8"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 2
}
